<template>
	<view class="signature-wrap">
		<view class="form">
				<view class="form-content" >
					<canvas class="form-content__canvas" canvas-id="canvas_sign" id="canvas_sign"
					 @touchstart="touchstart" :style="{height:canvasHeight+'px'}"
						@touchmove="touchmove" @touchend="touchend" disable-scroll="true"></canvas>
				</view>
	
				<view class="form-footer">
					<view class="sign-txt">请用户在上方空白处签名</view>
					<button class="form-footer__reset" @click="autographClick(1)">清空</button>
					<button class="form-footer__save" @click="autographClick(2)">保存</button>
					<!-- <button class="form-footer__preview" @click="autographClick(3)">预览</button> -->
				</view>
			</view>
	</view>
</template>

<script>
	import {toast} from '@/utils/utils.js';
	import {OREDR_STATUS} from '@/utils/global.js';
	import {mapStatus,mapMutations} from 'vuex'
	export default{
		data(){
			return {
				canvasCtx: '', //绘图图像
				points: [], //路径点集合
				hasSign: false,
				isInit: false,
				canvasHeight:100,
				orderId:'',
				userId:'',
				data:[],
				attachments:'',
				checkType:'',
				checkId:null
			}
		},
		onLoad(query) {
			//this.orderId = query.orderId;
			//this.userId = query.userId;
			uni.setNavigationBarColor({
				backgroundColor:'#f9ead5',
				frontColor: '#000000'
			});
			
			this.attachments = query.attachments;
			this.data = JSON.parse(query.data)
			this.checkType = query.checkType;
			this.checkId = query.id;
			
			
			this.canvasCtx = uni.createCanvasContext('canvas_sign', this) //创建绘图对象
			//设置画笔样式
			this.canvasCtx.lineWidth = 6
			// 设置线条的端点样式
			this.canvasCtx.lineCap = 'round'
			// 设置线条的交点样式
			this.canvasCtx.lineJoin = 'round';
			uni.getSystemInfo({
					success:(res=>{
							this.canvasHeight = res.windowHeight - uni.upx2px(60);
					})
			});
			// const systemInfo = uni.getWindowInfo;
			// this.canvasHeight = (systemInfo.safeAreaInsets.top + systemInfo.safeAreaInsets.bottom) +'px';
			console.log('canvasHeight',this.canvasHeight)
			uni.onWindowResize(onWinResize);

		},
		methods:{
			onWinResize(res){
				this.canvasHeight = res.windowHeight - uni.upx2px(60);
			},
			getBarHeight(){
					const res = uni.getSystemInfoSync()
					if(res.platform==='ios'){
							return 44+res.statusBarHeight
					}else if(res.platform==='android'){
							return 48+res.statusBarHeight
					}else{
							return 0;
					}
			},
			touchstart: function(e) {
				console.log('开始点')
					if (!this.isInit) {
						this.isInit = true
						this.autographClick(1);
					}
					let startX = e.changedTouches[0].x
					let startY = e.changedTouches[0].y
					let startPoint = {
						X: startX,
						Y: startY
					}
					this.points.push(startPoint)
					//每次触摸开始，开启新的路径
					this.canvasCtx.beginPath()
				},
				touchmove(e) {
					console.log('开始画点')
					let moveX = e.changedTouches[0].x
					let moveY = e.changedTouches[0].y
					let movePoint = {
						X: moveX,
						Y: moveY
					}
					this.points.push(movePoint) //存点
					let len = this.points.length
					if (len >= 2) {
						this.draw() //绘制路径
					}
	
				},
				touchend() {
					console.log('结束画点')
					this.points = []
					this.canvasCtx.draw(true)
				},
				draw() {
					let point1 = this.points[0]
					let point2 = this.points[1]
					this.points.shift()
					this.canvasCtx.moveTo(point1.X, point1.Y)
					this.canvasCtx.lineTo(point2.X, point2.Y)
					this.canvasCtx.stroke()
					this.canvasCtx.draw(true)
					this.hasSign = true
				},
				// 底部按钮点击操作
			autographClick(type) {
				let that = this
				if (type === 1) {
					//清空画布
					this.hasSign = false
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().select('.form-content__canvas')
							canvas.boundingClientRect().exec(function(data) {
								console.log('canvas', data)
								console.log('canvas wh:' + data[0].width + 'X' + data[0].height)
								let canvasw = Math.ceil(data[0].width)
								let canvash = Math.ceil(data[0].height)
								that.canvasCtx.fillStyle = '#fff'
								that.canvasCtx.fillRect(0, 0, canvasw, canvash)
								that.canvasCtx.draw(true)
							})
						}
					})

				} else {
					if (!this.hasSign) {
						uni.showToast({
							title: '签名不能为空',
							icon: 'none',
							duration: 2000
						})
						return
					}
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().select('.form-content__canvas')
							canvas.boundingClientRect().exec(function(data) {
								console.log('canvas saveSign:', data[0].width + 'X' + data[0].height)
								let canvasw = Math.ceil(data[0].width)
								let canvash = Math.ceil(data[0].height)
								uni.canvasToTempFilePath({
									destWidth: canvasw,
									destHeight: canvash,
									fileType: 'jpg',
									canvasId: 'canvas_sign',
									success: function(res) {
										console.log('图片导出成功：', res)
										let path = res.tempFilePath

										// 保存图片
										if (type === 2) {
											that.uploadPic(path)
										} else if (type === 3) {
											// 预览图片
											uni.previewImage({
												urls: [path]
											})
										}
									},
									fail: (err) => {
										// http://tmp/2LVQyvzddk2R820a9009dff43323d8e7fc9ef7a8d076.jpg
										console.log('图片导出失败：', err)
									}
								})
							})
						}
					})
				}
			},
			...mapMutations(['setOrderStatus']),
			// 图片上传处理
			uploadPic(tempFile) {
				// 1、将本地图片上传到服务器（假装是七牛云服务器）
				// 2、将七牛云返回的链接，上传到我们的服务器平台
				console.log("------:", tempFile);
				const token = wx.getStorageSync('token');
				const tenantId = wx.getStorageSync('tenantId_notice');
				const that = this;
				const url = this.$baseUrl+`/worksite-admin/minio/upload?token=${token}&tenantId=${tenantId}&module=signature`;
				console.log('---',url)
				uni.showLoading({title:'图片上传中...'});
				uni.uploadFile({
						url: url, //从调用页面传入 -- url: 'http://127.0.0.1:3000/' 后端接口地址
						filePath: tempFile, //从调用页面传入 --path: imgbox, 选取图片的地址数组  
						name: 'file', //文件名称可以自定义，要与后端配对使用：app.post('/',upload.single('img'),function(req,res,next)
						success: (resp) => {
							//图片上传成功，图片上传成功的变量+1
							const data = JSON.parse(resp.data);
							// that.imgUrls.push(data.data.url);
							// const eventChannel = that.getOpenerEventChannel(); // 兼容APP-NVUE
							// eventChannel.emit('onGetImgUrl',{url: data.data.url,type:that.type});
							let  saveaData ={
								
								    "sign": data.data.url,
								    "patrolItems":this.data,
									attachments:this.attachments
							}
							
							if(this.checkType==='year'){
								const  userId ={
									userId:this.checkId
								}
								console.log(saveaData)
								saveaData = {...saveaData,...userId}
								that.$API.liquefiedGasRoomYearCheck(saveaData).then(res => {
									uni.offWindowResize(onWinResize);
									uni.hideLoading()
									uni.showToast({title:'操作成功！'});
									uni.navigateBack({delta:2})
									
								});
							}else{
								const  orderId ={
									orderId:this.checkId
								}
								saveaData = {...saveaData,...orderId}
								that.$API.liquefiedGasOrderCheack(saveaData).then(res => {
									uni.hideLoading()
									uni.showToast({title:'操作成功！'});
									
									console.log(this.$store.getters.pageBackDelta)
									uni.navigateBack({delta:this.$store.getters.pageBackDelta})
									this.setOrderStatus(OREDR_STATUS[3]);
								});
							}
							     
						},
						fail: (fail) => {  //失败
							uni.hideLoading();
							toast('上传失败','error')
							console.log('fail:' ,fail);
						},
						complete: (e) => { //不论成功、失败都执行		
							uni.hideLoading();
							console.log('执行完毕');
						}
				});
				// setTimeout(() => {
				// 	uni.showToast({
				// 		title: '假装签名上传成功',
				// 		duration: 2000,
				// 		icon: 'none'
				// 	});
				// }, 1000);
			},
		}
	}
</script>

<style scoped lang="scss">
	@function tovmin($rpx) {
			@return #{$rpx * 100 / 750}vmin;
	}
	.signature-wrap{
		width: 100vw;height: 100vh;
		.form {
			display: flex;flex-direction: column;width: 100%;height: 100%;
				 .form-content {
					  width: 100%;height: 100%;
						&__canvas {
							// height: calc(100vh - tovmin(20) - tovmin(120) );
							// height: calc(100vh - tovmin(20) - tovmin(120) );
							width: 100vw;
						}
					}
					.form-footer {
						padding-top: tovmin(20);padding-bottom: tovmin(20);
						height: calc(tovmin(120) + constant(safe-area-inset-bottom));
						height: calc(tovmin(120) + env(safe-area-inset-bottom));
						width: 100%;display: flex;flex-direction: row;
						background: #FFFFFF;box-shadow: 0 tovmin(4) tovmin(20) tovmin(2) rgba(183, 183, 183, 0.20);
						button {width: 28vw;height: tovmin(88);
							line-height: tovmin(88);border-radius: tovmin(16);
							text-align: center;font-size: tovmin(36);font-weight: bold;
						}
						button::after {border: none;}
						.sign-txt{margin-left:tovmin(30);font-size: tovmin(36);color: #000000;font-weight: 500;height: tovmin(88);line-height: tovmin(88);}
						&__reset {color: #E02020;border: tovmin(1) solid #E02020;background-color:#ffffff; }
						&__save {background-color:#2986FF;color:#ffffff;}//background-image: linear-gradient(135deg, #1BC5FF 0%, #008AFE 100%)
						&__preview {color: #008AFE;border: tovmin(1) solid #008AFE;}
					}
			}
	}
</style>